package com.byd.sealmanage.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.byd.sealmanage.config.CommonResultOutput;
import com.byd.sealmanage.dao.mybatis.*;
import com.byd.sealmanage.modal.bo.EngraveApplyParamVo;
import com.byd.sealmanage.modal.bo.FilingSealExcelVO;
import com.byd.sealmanage.modal.bo.SearchUserVO;
import com.byd.sealmanage.modal.po.*;
import com.byd.sealmanage.service.DivisionSealService;
import com.byd.sealmanage.util.GlobalContants;
import com.byd.sealmanage.util.JsonUtil;
import com.byd.sealmanage.util.StringUtil;
import com.byd.sealmanage.util.UUIDGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class DivisionSealServiceImpl implements DivisionSealService {

    @Autowired
    private TbUserMapper tbUserMapper;

    @Autowired
    private TbProcessMapper tbProcessMapper;

    @Autowired
    private TbProcessRouteMapper tbProcessRouteMapper;

    @Autowired
    private TbProcessNodeMapper tbProcessNodeMapper;

    @Autowired
    private TbDivisionSealMapper tbDivisionSealMapper;

    @Autowired
    private TbKeepPeopleMapper tbKeepPeopleMapper;

    @Autowired
    private TbSealChangeMapper tbSealChangeMapper;

    /**
     * 刻制申请上传
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject engraveApplySubmit(Map<String,String> applyParam) {
        CommonResultOutput commonResultOutput;
        JSONObject jsonObject = new JSONObject();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date nowDate = new Date();
        try{
            System.out.println(applyParam);
            //1.创建申请流程
            TbProcess tbProcess = new TbProcess();
            String trackId = UUIDGenerator.getUUID();
            tbProcess.setTrackId(trackId);
            tbProcess.setProcessName(applyParam.get("topic"));
            tbProcess.setApplyNumber(applyParam.get("jobNumber"));
            tbProcess.setApplyName(applyParam.get("username"));
            tbProcess.setApplyEmail(applyParam.get("email"));
            tbProcess.setApplyDate(dateFormat.parse(applyParam.get("applyTime")));
            String[] approveNumbers = applyParam.get("approveNumber").split("-");
            tbProcess.setApproveNumber(approveNumbers[0]);
            tbProcess.setApproveName(approveNumbers[1]);
            TbUser approvePeople = tbUserMapper.getUserByJobNumber(approveNumbers[0],"1");
            tbProcess.setApproveEmail(approvePeople.getEmail());
            tbProcess.setProcessType("事业部内部印章刻制申请");
            tbProcess.setState("1");
            tbProcess.setApplyReason(applyParam.get("applyReason"));
            tbProcess.setPlace(applyParam.get("place"));
            tbProcess.setApplyFactory(applyParam.get("factory"));
            tbProcess.setApplyDepartment(applyParam.get("department"));
            tbProcessMapper.insertSelective(tbProcess);
            //2.创建流程节点
            List<TbProcessNode> processNodes = new ArrayList<>();
            List<TbProcessRoute> processRoutes = tbProcessRouteMapper.getProcessRouteByType("事业部内部印章刻制申请");
            for(int i = 0 ;i < 2; i++){
                TbProcessNode tbProcessNode = new TbProcessNode();
                tbProcessNode.setTrackId(trackId);
                if(i == 0){
                    tbProcessNode.setNodeName(processRoutes.get(i).getNodeName());
                    tbProcessNode.setConfirmNumber(applyParam.get("jobNumber"));
                    tbProcessNode.setConfirmName(applyParam.get("username"));
                    tbProcessNode.setConfirmEmail(applyParam.get("email"));
                    tbProcessNode.setReceiveTime(nowDate);
                    tbProcessNode.setApproveTime(nowDate);
                    tbProcessNode.setApproveRemark("提出申请");
                    tbProcessNode.setApproveResult("10");
                    tbProcessNode.setNodeState("0");
                }else{
                    tbProcessNode.setNodeName(processRoutes.get(i).getNodeName());
                    tbProcessNode.setConfirmNumber(approveNumbers[0]);
                    tbProcessNode.setConfirmName(approveNumbers[1]);
                    tbProcessNode.setConfirmEmail(approvePeople.getEmail());
                    tbProcessNode.setReceiveTime(nowDate);
                    tbProcessNode.setApproveResult("1");
                    tbProcessNode.setNodeState("1");
                }
                processNodes.add(tbProcessNode);
            }
            tbProcessNodeMapper.insertNodeList(processNodes);
            //3.创建印章信息
            //3.1申请的印章信息
            List<TbDivisionSeal> sealInfo = JSON.parseArray(applyParam.get("sealInfo"), TbDivisionSeal.class);
            for(TbDivisionSeal item : sealInfo){
                item.setTaskId(trackId);
                item.setStatus("1");
                item.setPlace(applyParam.get("place"));
                item.setFactory(applyParam.get("factory"));
            }
            tbDivisionSealMapper.insertSealList(sealInfo);
            commonResultOutput = new CommonResultOutput("0000","申请成功");
        }catch(Exception e){
            log.info("刻制申请接口出现异常");
            log.info(e.toString());
            commonResultOutput = new CommonResultOutput("9999", "申请失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚事务
        }
        return JsonUtil.toJSONObject(commonResultOutput);
    }

    /**
     * 根据工号或姓名查询人员
     * @param searchUserVO
     * @return
     */
    @Override
    public JSONObject getPeopleInfo(SearchUserVO searchUserVO) {
        CommonResultOutput commonResultOutput;
        JSONObject jsonObject = new JSONObject();
        try{
            int begin = (searchUserVO.getPage() - 1) * searchUserVO.getPageSize();
            searchUserVO.setBegin(begin);
            if(StringUtil.isNullString(searchUserVO.getJobnumber()) && StringUtil.isNullString(searchUserVO.getUsername())){
                jsonObject.put("total",0);
                commonResultOutput = new CommonResultOutput(999,"查询结果为空",jsonObject);
            }else{
                int count = tbUserMapper.selectSearchPeopleCount(searchUserVO);
                jsonObject.put("total",count);
                if(count > 0){
                    List<TbUser> data = tbUserMapper.selectSearchPeopleData(searchUserVO);
                    jsonObject.put("rows",data);
                    commonResultOutput = new CommonResultOutput(200,"查询成功",jsonObject);
                }else{
                    commonResultOutput = new CommonResultOutput(999,"查询结果为空",jsonObject);
                }
            }
        }catch (Exception e){
            log.info("查询人员接口出现异常");
            log.info(e.toString());
            commonResultOutput = new CommonResultOutput(999,"执行出现异常",jsonObject);
        }
        return JsonUtil.toJSONObject(commonResultOutput);
    }

    /**
     * 获取事业部刻制印章列表数据
     * @return
     */
    @Override
    public JSONObject getDivisionEngraveData(EngraveApplyParamVo engraveApplyParamVo,TbUser loginUser) {
        CommonResultOutput commonResultOutput;
        JSONObject jsonObject = new JSONObject();
        try{
            Integer begin = (engraveApplyParamVo.getPage() - 1) * engraveApplyParamVo.getPageSize();
            engraveApplyParamVo.setBegin(begin);
            int loginUserRole = 4;
            for(TbRole role : loginUser.getRoles()){
                loginUserRole = Integer.parseInt(role.getRoleId());
            }
            if(loginUserRole == 4){
                engraveApplyParamVo.setApplyPeople(loginUser.getJobnumber());
            }else if(loginUserRole == 3){
                if(StringUtil.isNullString(loginUser.getFactory())){
                    engraveApplyParamVo.setFactory(loginUser.getDepartment());
                }else{
                    engraveApplyParamVo.setFactory(loginUser.getFactory());
                }
            }else if(loginUserRole == 2){
                engraveApplyParamVo.setPlace(loginUser.getWorkPlace());
            }
            Integer totalCount = tbDivisionSealMapper.selectEngraveSealCount(engraveApplyParamVo);
            jsonObject.put("total",totalCount);
            if(totalCount > 0){
                List<EngraveApplyParamVo> tbDivisionSeals = tbDivisionSealMapper.selectEngraveSeal(engraveApplyParamVo);
                for(EngraveApplyParamVo engraveApplyParamVo1 : tbDivisionSeals){
                    String[] sealPictures = engraveApplyParamVo1.getSealPattern().split("sealPicture");
                    engraveApplyParamVo1.setSealPattern("localFile" + sealPictures[1]);
                }
                jsonObject.put("rows",tbDivisionSeals);
                commonResultOutput = new CommonResultOutput(200,"查询成功",jsonObject);
            }else{
                commonResultOutput = new CommonResultOutput(999,"查询结果为空",jsonObject);
            }
        }catch (Exception e){
            log.info("获取事业部客制化印章列表数据接口出现异常");
            log.info(e.toString());
            jsonObject.put(GlobalContants.MSG,"执行出现异常");
            commonResultOutput = new CommonResultOutput(999,"执行出现异常",jsonObject);
        }
        return JsonUtil.toJSONObject(commonResultOutput);
    }

    /**
     * 印章备案
     * @param map
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject sealFilingService(Map<String, String> map) {
        CommonResultOutput commonResultOutput;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        try{
            TbDivisionSeal sealData = tbDivisionSealMapper.selectByPrimaryKey(map.get("sealId"));
            String factoryInfo = map.get("factory");
            List<TbKeepPeople> keepPeopleInfo = JSON.parseArray(map.get("keepPeopleInfo"),TbKeepPeople.class);
            //添加监印人信息
            List<TbKeepPeople> keepPeopleList = new ArrayList<>();
            int keepCount = 0;
            for(TbKeepPeople item : keepPeopleInfo){
                keepCount += item.getKeepCount();
                String[] peopleInfo = item.getKeepNumber().split("-");
                TbUser keepUser = tbUserMapper.getUserByJobNumber(peopleInfo[0], "1");
                String nowFactory;
                if(StringUtil.isNullString(keepUser.getFactory())){
                    nowFactory = keepUser.getDepartment();
                }else{
                    nowFactory = keepUser.getFactory();
                }
                //判断监印人是否与印章属于同部门
                if(!factoryInfo.equals(nowFactory) || !sealData.getPlace().equals(keepUser.getWorkPlace())){
                    String message = "监印人" + peopleInfo[1] + "(" + peopleInfo[0] + ")的地区或工厂信息与印章不同";
                    commonResultOutput = new CommonResultOutput("9999",message);
                    return JsonUtil.toJSONObject(commonResultOutput);
                }else{
                    item.setKeepNumber(peopleInfo[0]);
                    item.setKeepName(peopleInfo[1]);
                    item.setCreateTime(date);
                    item.setSealId(map.get("sealId"));
                    item.setKeepFactory(keepUser.getFactory());
                    item.setKeepDepartment(keepUser.getDepartment());
                    item.setKeepOffice(keepUser.getOffice());
                    item.setState("3");
                    item.setWorkId(UUIDGenerator.getUUID());
                }
                keepPeopleList.add(item);
            }
            //判断监印数量与印章数量是否相等
            if(sealData.getSealCount() != keepCount){
                commonResultOutput = new CommonResultOutput("9999","监印数量与印章数量不符!");
                return JsonUtil.toJSONObject(commonResultOutput);
            }
            //更新印章记录表
            TbDivisionSeal tbDivisionSeal = new TbDivisionSeal();
            tbDivisionSeal.setSealId(map.get("sealId"));
            tbDivisionSeal.setEffect(map.get("effect"));
            tbDivisionSeal.setEngraveDate(dateFormat.parse(map.get("engraveDate")));
            String[] engravePeopleList = map.get("engravePeople").split("-");
            TbUser engravePeople = tbUserMapper.getUserByJobNumber(engravePeopleList[0], "1");
            String engraveFactory;
            if(StringUtil.isNullString(engravePeople.getFactory())){
                engraveFactory = engravePeople.getDepartment();
            }else{
                engraveFactory = engravePeople.getFactory();
            }
            if(!factoryInfo.equals(engraveFactory)){
                String message = "刻制人" + engravePeopleList[1] + "(" + engravePeopleList[0] + ")不属于" + factoryInfo;
                commonResultOutput = new CommonResultOutput("9999",message);
                return JsonUtil.toJSONObject(commonResultOutput);
            }
            tbDivisionSeal.setEngraveNumber(engravePeopleList[0]);
            tbDivisionSeal.setEngraveName(engravePeopleList[1]);
            String[] filingPeopleList = map.get("filingPeople").split("-");
            tbDivisionSeal.setFilingNumber(filingPeopleList[0]);
            tbDivisionSeal.setFilingName(filingPeopleList[1]);
            tbDivisionSeal.setStatus("3");
            tbDivisionSealMapper.updateByPrimaryKeySelective(tbDivisionSeal);
            //批量添加监印人信息
            tbKeepPeopleMapper.insertKeepPeopleList(keepPeopleList);
            commonResultOutput = new CommonResultOutput("0000","印章备案成功");
        }catch (Exception e){
            log.info("印章刻制处备案接口出现异常");
            log.info(e.toString());
            commonResultOutput = new CommonResultOutput("0000","执行出现异常");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return JsonUtil.toJSONObject(commonResultOutput);
    }

    /**
     * 获取实体印章备案信息
     * @param engraveApplyParamVo
     * @return
     */
    @Override
    public JSONObject getEntitySealService(EngraveApplyParamVo engraveApplyParamVo) {
        CommonResultOutput commonResultOutput;
        JSONObject jsonObject = new JSONObject();
        try{
            int begin = (engraveApplyParamVo.getPage() - 1) * engraveApplyParamVo.getPageSize();
            engraveApplyParamVo.setBegin(begin);
            engraveApplyParamVo.setSealType("实体印章");
            int totalCount = tbDivisionSealMapper.selectEntitySealCount(engraveApplyParamVo);
            jsonObject.put("total",totalCount);
            if(totalCount > 0){
                List<FilingSealExcelVO> entitySealList = tbDivisionSealMapper.selectEntitySealList(engraveApplyParamVo);
                for(FilingSealExcelVO item : entitySealList){
                    String[] sealPictures = item.getSealPattern().split("sealPicture");
                    item.setSealPattern("localFile" + sealPictures[1]);
                }
                jsonObject.put("rows",entitySealList);
                commonResultOutput = new CommonResultOutput(200,"查询成功",jsonObject);
            }else{
                commonResultOutput = new CommonResultOutput(999,"查询结果为空",jsonObject);
            }
        }catch (Exception e){
            log.info("获取实体印章备案信息接口出现接口");
            log.info(e.toString());
            commonResultOutput = new CommonResultOutput(999,"查询结果为空",jsonObject);
        }
        return JsonUtil.toJSONObject(commonResultOutput);
    }

    /**
     * 上传私自刻制的印章
     * @param file
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject uploadPersonalSealService(MultipartFile file) {
        CommonResultOutput commonResultOutput;
        Date date = new Date();
        try{
            String originalFilename = file.getOriginalFilename();
            log.info(originalFilename);
            ImportParams params = new ImportParams();
            params.setHeadRows(1);
            List<TbKeepPeople> keepPeopleList = new ArrayList<>();
            List<FilingSealExcelVO> sealInfos = ExcelImportUtil.importExcel(file.getInputStream(), FilingSealExcelVO.class, params);
            Iterator<FilingSealExcelVO> sealInfoList = sealInfos.iterator();
            while(sealInfoList.hasNext()){
                FilingSealExcelVO sealInfo = sealInfoList.next();
                if(StringUtil.isNullString(sealInfo.getSealId()) || StringUtil.isNullString(sealInfo.getSealPattern())){
                    sealInfoList.remove();
                }else{
                    sealInfo.setStatus("3");
                    TbKeepPeople keepPeopleInfo = new TbKeepPeople();
                    keepPeopleInfo.setSealId(sealInfo.getSealId());
                    keepPeopleInfo.setKeepNumber(sealInfo.getKeepNumber());
                    keepPeopleInfo.setKeepName(sealInfo.getKeepName());
                    keepPeopleInfo.setKeepFactory(sealInfo.getFactory());
                    keepPeopleInfo.setKeepDepartment(sealInfo.getDepartment());
                    keepPeopleInfo.setKeepOffice(sealInfo.getOffice());
                    keepPeopleInfo.setKeepCount(sealInfo.getSealCount());
                    keepPeopleInfo.setCreateTime(date);
                    keepPeopleInfo.setKeepRemark(sealInfo.getRemark());
                    keepPeopleInfo.setState("3");
                    keepPeopleInfo.setWorkId(UUIDGenerator.getUUID());
                    keepPeopleList.add(keepPeopleInfo);
                }
            }
            if(sealInfos.size() > 0){//是否添加校验备案人或刻制人
                List<FilingSealExcelVO> sealInfoLast = new ArrayList<>();
                sealFor:for(FilingSealExcelVO filingSealExcelVO : sealInfos){
                    if(sealInfoLast.size() == 0){
                        if(StringUtil.isNullString(filingSealExcelVO.getFactory())){
                            filingSealExcelVO.setFactory(filingSealExcelVO.getDepartment());
                        }
                        String noRealTaskId = UUIDGenerator.getUUID();
                        filingSealExcelVO.setTaskId(noRealTaskId);
                        sealInfoLast.add(filingSealExcelVO);
                    }else{
                        int forCount = 0;
                        for(FilingSealExcelVO item : sealInfoLast){
                            if(item.getSealId().equals(filingSealExcelVO.getSealId())){
                                Integer countSum = filingSealExcelVO.getSealCount() + item.getSealCount();
                                item.setSealCount(countSum);
                                continue sealFor;
                            }else{
                                forCount++;
                            }
                        }
                        if(forCount == sealInfoLast.size()){
                            if(StringUtil.isNullString(filingSealExcelVO.getFactory())){
                                filingSealExcelVO.setFactory(filingSealExcelVO.getDepartment());
                            }
                            String noRealTaskId = UUIDGenerator.getUUID();
                            filingSealExcelVO.setTaskId(noRealTaskId);
                            sealInfoLast.add(filingSealExcelVO);
                        }
                    }
                }
                for(TbKeepPeople people : keepPeopleList){
                    for(FilingSealExcelVO sealItem : sealInfoLast){
                        if(people.getSealId().equals(sealItem.getSealId())){
                            TbUser keepInfo = tbUserMapper.getUserByJobNumber(people.getKeepNumber(), "1");
                            String nowFactory = keepInfo.getFactory() + "-" + keepInfo.getDepartment() + "-" + keepInfo.getOffice();
                            String realFactory = sealItem.getFactory() + "-" + sealItem.getDepartment() + "-" + sealItem.getOffice();
                            if(!nowFactory.equals(realFactory) || !sealItem.getPlace().equals(keepInfo.getWorkPlace())){
                                String message = people.getKeepName() + "的地区或工厂信息与监管印章不符";
                                commonResultOutput = new CommonResultOutput(999, message);
                                return JsonUtil.toJSONObject(commonResultOutput);
                            }
                            people.setSealId(sealItem.getTaskId());
                        }
                    }
                }
                //插入印章
                tbDivisionSealMapper.insertFilingSealList(sealInfoLast);
                //批量联表插入监印人信息
                tbKeepPeopleMapper.insertKeepPeoplePersonal(keepPeopleList);
                commonResultOutput = new CommonResultOutput(200, "上传成功");
            }else{
                commonResultOutput = new CommonResultOutput(999, "上传的Excel有误");
            }
        }catch (Exception e){
            log.info("上传私印备案接口出现异常");
            log.info(e.toString());
            commonResultOutput = new CommonResultOutput(999,"执行出现异常");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return JsonUtil.toJSONObject(commonResultOutput);
    }

    /**
     * 印章转交
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject sealForwardService(Map<String,String> map,TbUser loginUser) {
        CommonResultOutput commonResultOutput;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        try{
            String[] receivePeople = map.get("receivePeople").split("-");
            List<FilingSealExcelVO> forwardSealList = JSON.parseArray(map.get("sealInfo"),FilingSealExcelVO.class);
            List<TbSealChange> changeRecord = new ArrayList<>();
            if("true".equals(map.get("isCrossPlace"))){
                //判断数量，如果数量等于库存，直接修改印章信息和监印人信息
                for(FilingSealExcelVO item : forwardSealList){
                    TbDivisionSeal tbDivisionSeal = tbDivisionSealMapper.selectByPrimaryKey(item.getSealId());
                    TbKeepPeople tbKeepPeople = tbKeepPeopleMapper.selectByPrimaryKey(item.getTfId());
                    //判断接收人是否与指定的科室和部门相同
                    TbUser receiveUserInfo = tbUserMapper.getUserByJobNumber(receivePeople[0], "1");
                    if(!StringUtil.isNullString(receiveUserInfo.getFactory())){
                        if(!map.get("factory").equals(receiveUserInfo.getFactory()) || !map.get("place").equals(receiveUserInfo.getWorkPlace())){
                            commonResultOutput = new CommonResultOutput("9999","接收人的地区与工厂信息与转交信息不同");
                            return JsonUtil.toJSONObject(commonResultOutput);
                        }
                    }else{
                        if(!map.get("factory").equals(receiveUserInfo.getDepartment()) || !map.get("place").equals(receiveUserInfo.getWorkPlace())){
                            commonResultOutput = new CommonResultOutput("9999","接收人的地区与工厂信息与转交信息不同");
                            return JsonUtil.toJSONObject(commonResultOutput);
                        }
                    }
                    TbSealChange tbSealChange = new TbSealChange();
                    if(tbDivisionSeal.getSealCount() < item.getSealCount()){
                        commonResultOutput = new CommonResultOutput("9999", "印章：" + item.getSealName() + "的转交数量超出了库存数量");
                        return JsonUtil.toJSONObject(commonResultOutput);
                    }else if(tbKeepPeople.getKeepCount() == item.getSealCount()){
                        if(tbDivisionSeal.getSealCount() == item.getSealCount()){//某个印章全部跨部门转交--情形1
                            tbSealChange.setState("1");
                            //修改印章部门
                            TbDivisionSeal updateSealInfo = new TbDivisionSeal();
                            updateSealInfo.setSealId(item.getSealId());
                            updateSealInfo.setPlace(map.get("place"));
                            updateSealInfo.setFactory(map.get("factory"));
//                            updateSealInfo.setDepartment(map.get("department"));
                            tbDivisionSealMapper.updateByPrimaryKeySelective(updateSealInfo);
                            //直接根据入的监印人主键id修改监印人信息
                            TbKeepPeople updateKeepPeople = new TbKeepPeople();
                            updateKeepPeople.setTfId(Integer.parseInt(item.getTfId()));
                            updateKeepPeople.setKeepNumber(receivePeople[0]);
                            updateKeepPeople.setKeepName(receivePeople[1]);
                            updateKeepPeople.setKeepFactory(receiveUserInfo.getFactory());
                            updateKeepPeople.setKeepDepartment(receiveUserInfo.getDepartment());
                            updateKeepPeople.setKeepOffice(receiveUserInfo.getOffice());
                            updateKeepPeople.setUpdateTime(date);
                            updateKeepPeople.setState("4");
                            tbKeepPeopleMapper.updateByPrimaryKeySelective(updateKeepPeople);
                        }else{//该印章只转交部分给某个部门---情形2
                            tbSealChange.setState("2");
                            //修改原部门印章数量
                            TbDivisionSeal oldSeal = new TbDivisionSeal();
                            oldSeal.setSealId(item.getSealId());
                            Integer leftCount = tbDivisionSeal.getSealCount() - item.getSealCount();
                            oldSeal.setSealCount(leftCount);
                            tbDivisionSealMapper.updateByPrimaryKeySelective(oldSeal);
                            //增加新的印章信息
                            TbDivisionSeal newSeal;
                            String trackId = UUIDGenerator.getUUID();
                            newSeal = tbDivisionSeal;
                            newSeal.setSealId(null);
                            newSeal.setTaskId(trackId);
                            newSeal.setSealCount(item.getSealCount());
                            newSeal.setPlace(map.get("place"));
                            newSeal.setFactory(map.get("factory"));
//                            newSeal.setDepartment(map.get("department"));
                            tbDivisionSealMapper.insertSelective(newSeal);
                            //直接根据入的监印人主键id修改监印人信息
                            TbKeepPeople updateKeepPeople = new TbKeepPeople();
                            updateKeepPeople.setTfId(Integer.parseInt(item.getTfId()));
                            updateKeepPeople.setSealId(trackId);
                            updateKeepPeople.setKeepNumber(receivePeople[0]);
                            updateKeepPeople.setKeepName(receivePeople[1]);
                            updateKeepPeople.setKeepFactory(receiveUserInfo.getFactory());
                            updateKeepPeople.setKeepDepartment(receiveUserInfo.getDepartment());
                            updateKeepPeople.setKeepOffice(receiveUserInfo.getOffice());
                            updateKeepPeople.setUpdateTime(date);
                            updateKeepPeople.setState("4");
                            tbKeepPeopleMapper.updateKeepPeopleOne(updateKeepPeople);
                        }
                        tbSealChange.setKeepWorkId(tbKeepPeople.getWorkId());
                    }else{//情形3
                        tbSealChange.setState("3");
                        //减少原部门印章数量
                        TbDivisionSeal oldSeal = new TbDivisionSeal();
                        oldSeal.setSealId(item.getSealId());
                        Integer leftCount = tbDivisionSeal.getSealCount() - item.getSealCount();
                        oldSeal.setSealCount(leftCount);
                        tbDivisionSealMapper.updateByPrimaryKeySelective(oldSeal);
                        //减少原监印人的印章数量
                        TbKeepPeople oldKeeper = new TbKeepPeople();
                        oldKeeper.setTfId(Integer.parseInt(item.getTfId()));
                        oldKeeper.setKeepCount(tbKeepPeople.getKeepCount() - item.getSealCount());
                        tbKeepPeopleMapper.updateByPrimaryKeySelective(oldKeeper);
                        //增加新的印章信息
                        TbDivisionSeal newSeal;
                        String trackId = UUIDGenerator.getUUID();
                        newSeal = tbDivisionSeal;
                        newSeal.setSealId(null);
                        newSeal.setTaskId(trackId);
                        newSeal.setSealCount(item.getSealCount());
                        newSeal.setPlace(map.get("place"));
                        newSeal.setFactory(map.get("factory"));
//                        newSeal.setDepartment(map.get("department"));
                        tbDivisionSealMapper.insertSelective(newSeal);
                        //添加监印人信息
                        TbKeepPeople addKeepPeople = new TbKeepPeople();
                        addKeepPeople.setSealId(trackId);
                        addKeepPeople.setKeepNumber(receivePeople[0]);
                        addKeepPeople.setKeepName(receivePeople[1]);
                        addKeepPeople.setKeepCount(item.getSealCount());
                        addKeepPeople.setKeepRemark(tbKeepPeople.getKeepRemark());
                        addKeepPeople.setCreateTime(date);
                        addKeepPeople.setKeepFactory(receiveUserInfo.getFactory());
                        addKeepPeople.setKeepDepartment(receiveUserInfo.getDepartment());
                        addKeepPeople.setKeepOffice(receiveUserInfo.getOffice());
                        addKeepPeople.setState("4");
                        String workId = UUIDGenerator.getUUID();
                        addKeepPeople.setWorkId(workId);
                        tbSealChange.setKeepWorkId(workId);
                        tbKeepPeopleMapper.insertKeepPeopleOne(addKeepPeople);
                    }
                    tbSealChange.setSealId(item.getSealId());
                    tbSealChange.setSealCount(item.getSealCount());
                    tbSealChange.setGetNumber(loginUser.getJobnumber());
                    tbSealChange.setGetName(loginUser.getUsername());
                    tbSealChange.setGetDate(dateFormat.parse(map.get("getDate")));
                    tbSealChange.setGetReason(map.get("getReason"));
                    tbSealChange.setReceiveNumber(receivePeople[0]);
                    tbSealChange.setReceiveName(receivePeople[1]);
                    tbSealChange.setOldKeepNumber(tbKeepPeople.getKeepNumber());
                    tbSealChange.setOldKeepName(tbKeepPeople.getKeepName());
                    tbSealChange.setOldKeepId(tbKeepPeople.getTfId());
                    changeRecord.add(tbSealChange);
                }
            }else{
                //非跨部门
                for(FilingSealExcelVO item : forwardSealList){
                    TbDivisionSeal tbDivisionSeal = tbDivisionSealMapper.selectByPrimaryKey(item.getSealId());
                    TbKeepPeople tbKeepPeople = tbKeepPeopleMapper.selectByPrimaryKey(item.getTfId());
                    //判断接收人是否与印章的科室和部门相同
                    TbUser receiveUserInfo = tbUserMapper.getUserByJobNumber(receivePeople[0], "1");
                    if(!StringUtil.isNullString(receiveUserInfo.getFactory())){
                        if(!tbDivisionSeal.getFactory().equals(receiveUserInfo.getFactory()) || !tbDivisionSeal.getPlace().equals(receiveUserInfo.getWorkPlace())){
                            commonResultOutput = new CommonResultOutput("9999","接收人的地区与工厂信息与印章不同");
                            return JsonUtil.toJSONObject(commonResultOutput);
                        }
                    }else{
                        if(!tbDivisionSeal.getFactory().equals(receiveUserInfo.getDepartment()) || !tbDivisionSeal.getPlace().equals(receiveUserInfo.getWorkPlace())){
                            commonResultOutput = new CommonResultOutput("9999","接收人的地区与工厂信息与印章不同");
                            return JsonUtil.toJSONObject(commonResultOutput);
                        }
                    }
                    TbSealChange tbSealChange = new TbSealChange();
                    if(tbKeepPeople.getKeepCount() < item.getSealCount()){
                        commonResultOutput = new CommonResultOutput("9999", "印章：" + item.getSealName() + "的转交数量超出了库存数量");
                        return JsonUtil.toJSONObject(commonResultOutput);
                    }else if(tbKeepPeople.getKeepCount() == item.getSealCount()){//情形4
                        tbSealChange.setState("4");
                        tbSealChange.setKeepWorkId(tbKeepPeople.getWorkId());
                        //直接根据入的监印人主键id修改监印人信息
                        TbKeepPeople updateKeepPeople = new TbKeepPeople();
                        updateKeepPeople.setTfId(Integer.parseInt(item.getTfId()));
                        updateKeepPeople.setKeepNumber(receivePeople[0]);
                        updateKeepPeople.setKeepName(receivePeople[1]);
                        updateKeepPeople.setKeepFactory(receiveUserInfo.getFactory());
                        updateKeepPeople.setKeepDepartment(receiveUserInfo.getDepartment());
                        updateKeepPeople.setKeepOffice(receiveUserInfo.getOffice());
                        updateKeepPeople.setUpdateTime(date);
                        updateKeepPeople.setState("4");
                        tbKeepPeopleMapper.updateByPrimaryKeySelective(updateKeepPeople);
                    }else{//情形5
                        tbSealChange.setState("5");
                        //减少原监印人的印章数量
                        TbKeepPeople updateKeepPeople = new TbKeepPeople();
                        updateKeepPeople.setTfId(Integer.parseInt(item.getTfId()));
                        Integer leftCount = tbKeepPeople.getKeepCount() - item.getSealCount();
                        updateKeepPeople.setKeepCount(leftCount);
                        updateKeepPeople.setUpdateTime(date);
                        tbKeepPeopleMapper.updateByPrimaryKeySelective(updateKeepPeople);
                        //添加监印人信息
                        TbKeepPeople newKeeper = new TbKeepPeople();
                        newKeeper.setSealId(tbKeepPeople.getSealId());
                        newKeeper.setKeepNumber(receivePeople[0]);
                        newKeeper.setKeepName(receivePeople[1]);
                        newKeeper.setKeepFactory(receiveUserInfo.getFactory());
                        newKeeper.setKeepDepartment(receiveUserInfo.getDepartment());
                        newKeeper.setKeepOffice(receiveUserInfo.getOffice());
                        newKeeper.setKeepCount(item.getSealCount());
                        newKeeper.setKeepRemark(tbKeepPeople.getKeepRemark());
                        newKeeper.setCreateTime(date);
                        newKeeper.setState("4");
                        String workId = UUIDGenerator.getUUID();
                        newKeeper.setWorkId(workId);
                        tbSealChange.setKeepWorkId(workId);
                        tbKeepPeopleMapper.insertSelective(newKeeper);
                    }
                    tbSealChange.setSealId(tbKeepPeople.getSealId());
                    tbSealChange.setSealCount(item.getSealCount());
                    tbSealChange.setGetNumber(loginUser.getJobnumber());
                    tbSealChange.setGetName(loginUser.getUsername());
                    tbSealChange.setGetDate(dateFormat.parse(map.get("getDate")));
                    tbSealChange.setGetReason(map.get("getReason"));
                    tbSealChange.setReceiveNumber(receivePeople[0]);
                    tbSealChange.setReceiveName(receivePeople[1]);
                    tbSealChange.setOldKeepNumber(tbKeepPeople.getKeepNumber());
                    tbSealChange.setOldKeepName(tbKeepPeople.getKeepName());
                    tbSealChange.setOldKeepId(tbKeepPeople.getTfId());
                    changeRecord.add(tbSealChange);
                }
            }
            //批量插入转交记录
            tbSealChangeMapper.insertChangeList(changeRecord);
            commonResultOutput = new CommonResultOutput("0000","印章转交成功");
        }catch(Exception e){
            log.info("印章转交接口出现异常");
            log.info(e.toString());
            commonResultOutput = new CommonResultOutput("9999","执行出现异常");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return JsonUtil.toJSONObject(commonResultOutput);
    }


}
